﻿using AutoMapper;
using Consul;
using EWC.Core.DependencyInjection;
using EWC.Core.Util.CustomException;
using EWC.HIS.Application.Contracts.AppointmentRegistrationService.Commands;
using EWC.HIS.Domain;
using EWC.HIS.Domain.Data.Uow;
using EWC.HIS.Domain.Entities;
using EWC.HIS.Domain.Repositories;
using EWC.HIS.Domain.Users;
using EWC.HIS.Domain.Users.Entities;
using MediatR;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace EWC.HIS.Application.AppointmentRegistrations.Handlers
{
    public class AddAppointmentRegistrationCommandHandler : IRequestHandler<AddAppointmentRegistrationCommand, int>, IScopedDependency
    {
        private readonly IMapper _mapper;
        private readonly IAppointmentRegistrationRepository _appointmentRegistrationRepository;
        private readonly IUserRepository _userRepository;
        private readonly IUnitOfWork _unitOfWork;

        public AddAppointmentRegistrationCommandHandler(IMapper mapper, IAppointmentRegistrationRepository appointmentRegistrationRepository, IUserRepository userRepository, IUnitOfWork unitOfWork)
        {
            _mapper = mapper;
            _appointmentRegistrationRepository = appointmentRegistrationRepository;
            _userRepository = userRepository;
            _unitOfWork = unitOfWork;
        }

        public async Task<int> Handle(AddAppointmentRegistrationCommand request, CancellationToken cancellationToken)
        {
            await _unitOfWork.BeginTransactionAsync();
            int result = 0;
            try
            {
                var user = new User
                {
                    Name = "jack"
                };
                await _userRepository.InsertAsync(user, null);

                var appointmentRegistration = _mapper.Map<AppointmentRegistration>(request.RegistrationDto);
                appointmentRegistration.CreationTime = DateTime.Now;
                result = await _appointmentRegistrationRepository.InsertAsync(appointmentRegistration, null);

                await _unitOfWork.CommitAsync();
            }
            catch (Exception)
            {
                await _unitOfWork.RollbackAsync();
            }
            finally
            {
                await _unitOfWork.DisposeAsync();
            }
            return result;
        }

    }
}
